package com.itheima.prize.api.action;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.prize.commons.config.RedisKeys;
import com.itheima.prize.commons.db.entity.CardUser;
import com.itheima.prize.commons.db.mapper.CardUserMapper;
import com.itheima.prize.commons.db.service.CardUserService;
import com.itheima.prize.commons.utils.ApiResult;
import com.itheima.prize.commons.utils.PasswordUtil;
import com.itheima.prize.commons.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping(value = "/api")
@Api(tags = {"登录模块"})
public class LoginController {
    @Autowired
    private CardUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation(value = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="account",value = "用户名",required = true),
            @ApiImplicitParam(name="password",value = "密码",required = true)
    })
    public ApiResult login(HttpServletRequest request, @RequestParam String account,@RequestParam String password) {
        //从Redis中取错误次数
        Integer errorTimes = (Integer) redisUtil.get(RedisKeys.USERLOGINTIMES+account);
        if (errorTimes != null && errorTimes > 5){
           return new ApiResult(0,"密码错误5次，请5分钟后再登录",null);
        }

        //登录操作
            //往数据库中存入用户信息
        QueryWrapper<CardUser> wrapper = new QueryWrapper<>();
        wrapper.eq("uname",account).eq("passwd",PasswordUtil.encodePassword(password));   //采用md5加密
        List<CardUser> users = userService.list(wrapper);
        if(users != null && users.size() > 0){
            //信息脱敏：密码打码(如：138****5678 )
            CardUser user = users.get(0);
            user.setPasswd(null);
            user.setIdcard("打码**null");
            //用的是集成spring redis session，会session放入redis当中去，让集群分布式模式下也能拿到session
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            return new ApiResult(1,"登录成功",user);
        }else{
            //登录失败
            redisUtil.incr(RedisKeys.USERLOGINTIMES+account,1); //失败一次，计数增加一次
            /*
            如果 5 分钟内没有再输错密码，这个 key 会自动消失，错误次数会被清零。
            如果 5 分钟内又输错一次，过期时间会被刷新为新的 5 分钟
            * */
            redisUtil.expire(RedisKeys.USERLOGINTIMES+account,60*5); //每输错一次，都会把(RedisKeys.USERLOGINTIMES+account)过期时间“刷新”为5分钟
            return new ApiResult(0,"账户名或密码错误",null);
        }
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出")
    public ApiResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null){
            session.invalidate();
        }
        return new ApiResult(1,"退出成功",null);
    }

}